package gui;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import serial.SerialException;
import serial.SerialInterface;
import serial.SerialReaderListener;

@SuppressWarnings("serial")
public class MemoryFrame extends JFrame implements ActionListener, SerialReaderListener  {
	
	private JTextField available, used, total;
	private JButton refresh;
	private SerialInterface serial;
	
	public MemoryFrame(SerialInterface serial) {
		setTitle("NXT Memory Usage (bytes)");
		setSize(300, 200);
		setLayout(new GridLayout(4, 1));
		
		available = makePanel("Available");
		used = makePanel("In use");
		total = makePanel("Total");
		
		refresh = new JButton("Refresh");
		refresh.addActionListener(this);
		add(refresh);
		
		serial.addSerialReaderListener(this);
		this.serial = serial;
	}
	
	private JTextField makePanel(String label) {
		JPanel panel = new JPanel();
		panel.add(new JLabel(label));
		JTextField field = new JTextField("(unknown)");
		panel.add(field);
		field.setEditable(false);
		add(panel);
		return field;
	}

	@Override
	public void halted() {
	}

	@Override
	public void stringReceived(String input) {
		Scanner s = new Scanner(input);
		while (s.hasNextLine()) {
			String line = s.nextLine();
			String[] nums = line.split("\\s+");
			if (nums.length == 6) {
				try {
					// Values from pbLua are in 8-byte blocks
					int totalMem = 8 * Integer.parseInt(nums[3]);
					int inUse = 8 * Integer.parseInt(nums[4]);
					int remaining = 8 * Integer.parseInt(nums[5]);
					
					available.setText(Integer.toString(remaining));
					used.setText(Integer.toString(inUse));
					total.setText(Integer.toString(totalMem));
					
				} catch (NumberFormatException nfe) {
				}
			}
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		requestInfo();
	}

	public void requestInfo() {
		try {
			serial.send("print(nxt.HeapInfo())\n", false, true);
		} catch (SerialException e1) {
			JOptionPane.showMessageDialog(this, "Can't communicate with NXT");
		}
	}
}
